package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-11
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;

    @Autowired
    IApUserFollowService userFollowService;

    @Override
    public ResponseResult login(LoginDto dto) {

        if (dto == null || (dto.getEquipmentId() == null || dto.getPassword() == null || dto.getPhone() == null)) {

            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {

            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();

            query.eq(ApUser::getPhone, dto.getPhone());

            ApUser one = this.getOne(query);

            if (one == null) {

                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 存在,获取盐,使用用户传入的密码+盐 进行md5计算
            String salt = one.getSalt();

            String pwdStr = dto.getPassword() + salt;

            String md5Str = DigestUtils.md5DigestAsHex(pwdStr.getBytes());

            if (!md5Str.equals(one.getPassword())) {

                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            Map<String, Object> map = new HashMap<>();

            map.put("userId", one.getId());

            map.put("userName", one.getName());

            String token = AppJwtUtil.getToken(map);

            Map<String, Object> map1 = new HashMap<>();

            one.setPhone(null);

            one.setSalt(null);

            one.setPassword(null);

            map1.put("user", one);

            map1.put("token", token);

            return ResponseResult.okResult(map1);
        }
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {

            Map<String, Object> claimMap = new HashMap<>();

            claimMap.put("userId", 0);

            String token = AppJwtUtil.getToken(claimMap);

            Map<String, Object> map = new HashMap<>();

            map.put("token", token);

            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        User user = AppThreadLocalUtil.get();

        if (user == null) {

            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        int followId = 0;

        ApUserFollow userFollow = new ApUserFollow();

        userFollow.setUserId(user.getUserId());
        userFollow.setUserName(user.getUserName());
        userFollow.setLevel(1);
        userFollow.setCreatedTime(new Date());

        ResponseResult<ApAuthor> author = articleFeign.getAuthorById(dto.getAuthorId());

        if (author.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {

            ApAuthor data = author.getData();

            if (data != null) {

                userFollow.setFollowId(data.getUserId());

                userFollow.setFollowName(data.getName());

                Integer userId = data.getUserId();

                LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();

                query.eq(ApUserFollow::getUserId, user.getUserId());

                query.eq(ApUserFollow::getFollowId, data.getUserId());

                if (dto.getOperation() == 0) {

                    ApUserFollow one = userFollowService.getOne(query);

                    if (one == null) {

                        userFollowService.save(userFollow);
                    }
                } else {

                    userFollowService.remove(query);
                }
            }
        }

        // 将操作行为发送到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(followId);
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setOperation(dto.getOperation());

        String msg = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehaviorTopic, msg);

        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
